package com.jqb.servletlab.servlet;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class DownloadServlet extends HttpServlet {
	
	private static final long serialVersionUID = 2484013174512720208L;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		String filename = req.getParameter("filename");
		System.out.println("filename="+filename);
		//防止盗链
		String referer=req.getHeader("referer");
		if(referer==null||!referer.startsWith("http://localhost/test")){
//			resp.setStatus(302);
//			resp.setHeader("Location", "/test/errorPage");
//			上面2行等于下面一行
			resp.sendRedirect("/test/errorPage");
		}
		//解决在下载框中显示中文文件名的问题
		String showName = new String(filename.getBytes("utf-8"),"ISO8859-1");
		//告诉浏览器用户需要下载文件,弹出下载框
		resp.setHeader("Content-Disposition", "attachment;filename="+showName);
		
		String filePath =this.getServletContext().getRealPath("/Download");
		File file = new File(filePath,filename);
		
		FileInputStream fis = new FileInputStream(file);
		OutputStream os = resp.getOutputStream();
		
		byte[] buf = new byte[1024];
		int len = 0;
		while((len=fis.read(buf))>0){
			os.write(buf, 0, len);
		}
		os.close();
		fis.close();
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doGet(req,resp);
	}
	
}
